package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import io.swagger.annotations.Api;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

@Service
@Slf4j
@Transactional
public class WmMaterServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial>implements WmMaterialService {
   @Autowired
   private FastDFSClient fastDFSClient;

    @Value("${fdfs.url}")
    private String fileServerUrl;
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //检查参数
        if(multipartFile==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前登录用户
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if(wmUser==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //上传图片到fasfdfs
        String fileId=null;
        try {
          fileId=fastDFSClient.uploadFile(multipartFile);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        //保存素材数据到表中 wm_material
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setUserId(wmUser.getId());
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        //拼接图片路径
        wmMaterial.setUrl(fileServerUrl+fileId);
        return ResponseResult.okResult(wmMaterial);
    }
}
